/*
 * AuthFilter.java  2012-2-13
 * 
 * Copyright(c) 2011 First 工作室  All Rights Reserved.
 */
package com.first.core.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.first.core.Constants;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * <p>
 * Description
 * </p>
 * 
 * @author jonny
 * @version 1.0
 */
public class AuthFilter implements Filter {

	Logger log = Logger.getLogger(AuthFilter.class.getName());

	//需要登陆验证的页面
	List<String> includePages;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		/*
		 * 如果处理HTTP请求，并且需要访问诸如getHeader或getCookie等在ServletRequest中
		 * 无法得到的方法，就要把此request对象转型为HttpServletRequest
		 */
		HttpServletResponse resp = (HttpServletResponse) response;
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession(false);
		
		String currentUrl = req.getRequestURI();//获取当前访问的url
		//只过滤jsp或action请求
		if(currentUrl.indexOf(".jsp") > -1 || currentUrl.indexOf(".do") > -1){
			boolean isInclude = false;
			for (Iterator iterator = includePages.iterator(); iterator.hasNext();) {
				String pageOrURL = (String) iterator.next();
				if(currentUrl.indexOf(pageOrURL) > -1 ){
					isInclude = true;
					break;
				}
			}
			
			if(isInclude){
				log.debug("对jsp文件进行权限验证。" + "请求的URL：" + currentUrl);
				
				if(session == null || session.getAttribute(Constants.SESSION_UESR) == null){
					resp.sendRedirect(req.getContextPath() + "/logout.do");
					return;
				}
			}
		}
		
		//加入filter链继续向下执行
		chain.doFilter(request, response);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		/** 
         * 初始化 
         */  
        String configPath = filterConfig.getInitParameter("configPath");         
        String realConfigPath = filterConfig.getServletContext().getRealPath(configPath);        
        FileInputStream input;  
        byte buff[]=null;  
        try {  
            input = new FileInputStream(realConfigPath);  
            buff=new byte[input.available()];             
            input.read(buff);  
            input.close();  
              
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }         
        /** 
         * 通过开源XStream来解析XML，并转化成Java对象 
         */  
        XStream xstream = new XStream(new DomDriver());   
        xstream.alias("PageList", ArrayList.class);    
        xstream.alias("includePage", String.class);    
        includePages = (List)xstream.fromXML(new String(buff));
		log.debug("初始化权限过滤器。");
	}

}
